/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.elcom.emocbc.blacklist.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author GiangLT
 */
public class BlacklistDao {
    
    private static BlacklistDao instance;
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final DbAccess dbAccess = DbAccess.getInstance();
    protected Connection connection;
    
    private BlacklistDao() {
    }
    
    public static synchronized BlacklistDao getInstance() {
        if (instance == null) {
            instance = new BlacklistDao();
        }
        return instance;
    }
    
    protected synchronized Connection getConnection() throws SQLException {
//        Connection connection = null;
        if (connection != null && !connection.isClosed()) {
            return connection;
        }
        int retry = 0;
        connection = null;
        while ((connection == null || connection.isClosed()) && retry < 3) {
            connection = dbAccess.getConnection();
            if (connection != null) {
                break;
            }
            retry++;
            try {
                Thread.sleep(5000); // Tam nghi 5s
            } catch (InterruptedException ex) {
                logger.error("", ex);
            }
        }
        return connection;
    }
    
    public synchronized Set<String> findAll() throws SQLException {
        Set<String> result = new TreeSet<String>();
        Connection con = getConnection();
        if (con == null) {
            throw new SQLException("Cannot get connection");
        }
        PreparedStatement ps = null;
        try {
            String cmd = "SELECT msisdn FROM " + getTableName() + " ORDER BY msisdn";
            ps = con.prepareStatement(cmd);
            ResultSet rs = ps.executeQuery();
            
            while (rs.next()) {
                result.add(rs.getString("msisdn"));
            }
            rs.close();
        } finally {
            DbAccess.closePreparedStatement(ps);
            DbAccess.closeConnection(con);
        }
        return Collections.synchronizedSet(result);
    }
    
    private String getTableName() {
        return "blacklist";
    }
}
